<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring Security,">










<meta name="description" content="Spring Security 是一个可以为基于Spring的应用系统提供声明式的安全访问控制的安全框架。     它提供一组可在上下文配置的Bean，通过这些扩展和配置这些Bean，我们可以实现功能强大的、高度定制化的身份验证和访问的控制框架。     本篇将会分析 Spring Security 处理认证和权限校验的的过滤器及其实现。">
<meta name="keywords" content="Spring Security">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring  Security 源码分析三">
<meta property="og:url" content="http://sangaizhi.gitee.io/2018/12/16/2018-12-16-Spring-Security-Source-Analysis-3/index.html">
<meta property="og:site_name" content="sangaizhi-blog">
<meta property="og:description" content="Spring Security 是一个可以为基于Spring的应用系统提供声明式的安全访问控制的安全框架。     它提供一组可在上下文配置的Bean，通过这些扩展和配置这些Bean，我们可以实现功能强大的、高度定制化的身份验证和访问的控制框架。     本篇将会分析 Spring Security 处理认证和权限校验的的过滤器及其实现。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-12-16T15:48:56.989Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring  Security 源码分析三">
<meta name="twitter:description" content="Spring Security 是一个可以为基于Spring的应用系统提供声明式的安全访问控制的安全框架。     它提供一组可在上下文配置的Bean，通过这些扩展和配置这些Bean，我们可以实现功能强大的、高度定制化的身份验证和访问的控制框架。     本篇将会分析 Spring Security 处理认证和权限校验的的过滤器及其实现。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://sangaizhi.gitee.io/2018/12/16/2018-12-16-Spring-Security-Source-Analysis-3/">





  <title>Spring  Security 源码分析三 | sangaizhi-blog</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">sangaizhi-blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://sangaizhi.gitee.io/2018/12/16/2018-12-16-Spring-Security-Source-Analysis-3/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sangaizhi">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="sangaizhi-blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Spring  Security 源码分析三</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-16T23:06:55+08:00">
                2018-12-16
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/spring-security/" itemprop="url" rel="index">
                    <span itemprop="name">spring security</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <pre><code>Spring Security 是一个可以为基于Spring的应用系统提供声明式的安全访问控制的安全框架。
    它提供一组可在上下文配置的Bean，通过这些扩展和配置这些Bean，我们可以实现功能强大的、高度定制化的身份验证和访问的控制框架。
    本篇将会分析 Spring Security 处理认证和权限校验的的过滤器及其实现。
</code></pre><a id="more"></a>
<p>&emsp;&emsp;一开始先分析 <code>AbstractSecurityInterceptor</code> 的实现，因为请求的拦截是否具体的子类进行拦截的，然后调用父类的方法进行认证、鉴权和修改返回结果等操作。</p>
<h3 id="一、FilterSecurityInterceptor"><a href="#一、FilterSecurityInterceptor" class="headerlink" title="一、FilterSecurityInterceptor"></a>一、FilterSecurityInterceptor</h3><h4 id="1、主要职能"><a href="#1、主要职能" class="headerlink" title="1、主要职能"></a>1、主要职能</h4><p>&emsp;&emsp;<code>FilterSecurityInterceptor</code>在 Spring Security 的过滤器链中担任着非常重要的角色，它是我们自身 REST 服务的守门员，<code>FilterSecurityInterceptor</code> 将用于受保护的 Web 请求。在这个类里面，Spring  Security 会判断当前的请求是否能够有权限访问我们的REST服务，并且会通过代理的方式去调用我们的 REST 服务。</p>
<h4 id="2、主要步骤"><a href="#2、主要步骤" class="headerlink" title="2、主要步骤"></a>2、主要步骤</h4><p>&emsp;&emsp;<code>FilterSecurityInterceptor</code>处理请求主要通过 <code>invoke()</code> 方法来完成，处理思路就是在调用目标REST服务的前后添加一些操作。具体的实现步骤如下：<br>&emsp;&emsp;1). 首先，判断当前的这个过滤器是否已经处理过该请求，只有没有处理过得请求才会被处理。<br>&emsp;&emsp;2). 其次，在该方法中会调用父类的 <code>beforeInvocation()</code> 方法执行一个认证和权限的校验。<br>&emsp;&emsp;3). 第三，不管调用目标服务是否发生问题（异常），都需要执行恢复在 <code>beforeInvocation()</code>方法中修改的 <code>SecurityContext</code>.<br>&emsp;&emsp;4). 最后，处理请求返回的结果，如果有注入 <code>AfterInvocationManager</code>，就会调用它的 <code>decide()</code> 方法决定返回的结果。<br>核心代码如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">invoke</span><span class="params">(FilterInvocation fi)</span> <span class="keyword">throws</span> IOException, ServletException </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> ((fi.getRequest() != <span class="keyword">null</span>) &amp;&amp; (fi.getRequest().getAttribute(FILTER_APPLIED) != <span class="keyword">null</span>) &amp;&amp; observeOncePerRequest) &#123;</span><br><span class="line">        <span class="comment">// 1) 判断针对当前的请求该过滤器是否已经执行，</span></span><br><span class="line">  	fi.getChain().doFilter(fi.getRequest(), fi.getResponse());</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 第一次执行</span></span><br><span class="line">	<span class="keyword">if</span> (fi.getRequest() != <span class="keyword">null</span>) &#123;</span><br><span class="line">		fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE);</span><br><span class="line">	&#125;</span><br><span class="line">        <span class="comment">// 2) 调用 REST 服务前的认证及权限校验操作</span></span><br><span class="line">	InterceptorStatusToken token = <span class="keyword">super</span>.beforeInvocation(fi);</span><br><span class="line">	<span class="keyword">try</span> &#123;</span><br><span class="line">		fi.getChain().doFilter(fi.getRequest(), fi.getResponse());</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">finally</span> &#123;</span><br><span class="line">                <span class="comment">// 3) 恢复 SecurityContext</span></span><br><span class="line">		<span class="keyword">super</span>.finallyInvocation(token);</span><br><span class="line">	&#125;</span><br><span class="line">        <span class="comment">// 4) 处理返回结果</span></span><br><span class="line">	<span class="keyword">super</span>.afterInvocation(token, <span class="keyword">null</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>&emsp;&emsp;在 <code>invoke()</code> 方法中，最重要也是最核心的步骤就是第2步，调用父类 <code>AbstractSecurityInterceptor</code> 的 <code>beforeInvocation()</code>方法进行用户验证。<code>beforeInvocation()</code> 方法具体的逻辑在 <code>AbstractSecurityInterceptor</code> 中分析。</p>
<h3 id="二、-MethodSecurityInterceptor"><a href="#二、-MethodSecurityInterceptor" class="headerlink" title="二、 MethodSecurityInterceptor"></a>二、 MethodSecurityInterceptor</h3><p>&emsp;&emsp;用于受保护的方法的调用，<strong><font color="#e00" size="72">暂未完成</font></strong></p>
<h3 id="三、AbstractSecurityInterceptor"><a href="#三、AbstractSecurityInterceptor" class="headerlink" title="三、AbstractSecurityInterceptor"></a>三、AbstractSecurityInterceptor</h3><p>&emsp;&emsp;<code>AbstractSecurityInterceptor</code>这个抽象父类主要是实现一些公用的方法供子类调用，其中主要的几个方法如下：</p>
<h4 id="1、-beforeInvocation-方法"><a href="#1、-beforeInvocation-方法" class="headerlink" title="1、 beforeInvocation() 方法"></a>1、 beforeInvocation() 方法</h4><p>&emsp;&emsp;<code>beforeInvocation()</code> 方法主要都是做了一些在真正请求受保护对象之前的一些必要操作，这个操作包含以下几个：<br>&emsp;&emsp;1). 判断请求的受保护的对象是不是当前过滤器配置的受保护的对象；<br>&emsp;&emsp;2). 获取配置的权限信息；<br>&emsp;&emsp;3). 认证用户的身份；<br>&emsp;&emsp;4). 进行目标资源的权限认证；<br>&emsp;&emsp;5). 使用上下文原有的用户信息和权限信息构建一个新的 Authentication；<br>&emsp;&emsp;6). 使用新的 Authentication 信息替换 SecurityContext 中的 AUthentication 信息。<br>下面是 <code>beforeInvocation()</code> 的方法的具体代码：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> InterceptorStatusToken <span class="title">beforeInvocation</span><span class="params">(Object object)</span> </span>&#123;</span><br><span class="line">  <span class="comment">// 1) 当前被判断的对象是不是要判断的对象</span></span><br><span class="line">  <span class="keyword">if</span> (!getSecureObjectClass().isAssignableFrom(object.getClass())) &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</span><br><span class="line">      <span class="string">"Security invocation attempted for object "</span> + object.getClass().getName()</span><br><span class="line">          + <span class="string">" but AbstractSecurityInterceptor only configured to support secure objects of type: "</span></span><br><span class="line">          + getSecureObjectClass());</span><br><span class="line">    &#125;</span><br><span class="line">  <span class="comment">// 2) 取出配置的权限信息，权限信息的来源 ExpressionUrlAuthorizationConfigurer</span></span><br><span class="line">  <span class="comment">// 或者  UrlAuthorizationConfigurer 两个配置类的配置的权限信息</span></span><br><span class="line">  Collection&lt;ConfigAttribute&gt; attributes = <span class="keyword">this</span>.obtainSecurityMetadataSource().getAttributes(object);</span><br><span class="line">  <span class="comment">// 针对当前的过滤器 (FilterSecurityInterceptor) 没有配置权限信息，表示该烂机器不允许进行公共调用</span></span><br><span class="line">  <span class="keyword">if</span> (attributes == <span class="keyword">null</span> || attributes.isEmpty()) &#123;</span><br><span class="line">    <span class="keyword">if</span> (rejectPublicInvocations) &#123;</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</span><br><span class="line">          <span class="string">"Secure object invocation "</span> + object   + <span class="string">" was denied as public invocations are not allowed via this interceptor. "</span></span><br><span class="line">              + <span class="string">"This indicates a configuration error because the "</span></span><br><span class="line">              + <span class="string">"rejectPublicInvocations property is set to 'true'"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    publishEvent(<span class="keyword">new</span> PublicInvocationEvent(object));</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>; <span class="comment">// no further work post-invocation</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (SecurityContextHolder.getContext().getAuthentication() == <span class="keyword">null</span>) &#123;</span><br><span class="line">    credentialsNotFound(messages.getMessage(</span><br><span class="line">      <span class="string">"AbstractSecurityInterceptor.authenticationNotFound"</span>,  <span class="string">"An Authentication object was not found in the SecurityContext"</span>), object, attributes);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 3). 使用 AuthenticationManager 对当前的用户的身份进行认证，会使用具体的 AuthenticationProvider进行认证，具体的认证步骤在下一篇分析</span></span><br><span class="line">  Authentication authenticated = authenticateIfRequired();</span><br><span class="line">  <span class="comment">// 4) 资源的权限认证</span></span><br><span class="line">  <span class="keyword">try</span> &#123;</span><br><span class="line">    <span class="keyword">this</span>.accessDecisionManager.decide(authenticated, object, attributes);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">catch</span> (AccessDeniedException accessDeniedException) &#123;</span><br><span class="line">    publishEvent(<span class="keyword">new</span> AuthorizationFailureEvent(object, attributes, authenticated, accessDeniedException));</span><br><span class="line">    <span class="keyword">throw</span> accessDeniedException;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (publishAuthorizationSuccess) &#123;</span><br><span class="line">    publishEvent(<span class="keyword">new</span> AuthorizedEvent(object, attributes, authenticated));</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 5) 使用原有的 Authentication 信息和权限信息构建一个新的 Authentication 信息</span></span><br><span class="line">  Authentication runAs = <span class="keyword">this</span>.runAsManager.buildRunAs(authenticated, object, attributes);</span><br><span class="line">  <span class="keyword">if</span> (runAs == <span class="keyword">null</span>) &#123;</span><br><span class="line">    <span class="comment">// 构建新的 Authentication 信息失败了</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> InterceptorStatusToken(SecurityContextHolder.getContext(), <span class="keyword">false</span>, attributes, object);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 6) 替换原有 SecurityContext中的 Authentication信息</span></span><br><span class="line">    SecurityContext origCtx = SecurityContextHolder.getContext();</span><br><span class="line">    SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());</span><br><span class="line">    SecurityContextHolder.getContext().setAuthentication(runAs);</span><br><span class="line">    <span class="comment">// need to revert to token.Authenticated post-invocation</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> InterceptorStatusToken(origCtx, <span class="keyword">true</span>, attributes, object);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在 <code>beforeInvocation()</code> 方法中，出现了几个比较重要的参数：</p>
<h5 id="1-ConfigAttribute"><a href="#1-ConfigAttribute" class="headerlink" title="1. ConfigAttribute"></a>1. ConfigAttribute</h5><p>&emsp;&emsp;从上面的分析可以看出，<code>beforeInvocation()</code>方法中进行鉴权的时候使用的 <code>AccessDecisionManager</code>的 <code>decide()</code>方法实现的。<code>decide()</code> 方法是需要接受当前的用户信息、受保护的对象以及受保护对象对应的的 <code>ConfigAttribute</code>集合作为参数进行鉴权。具体的 <code>ConfigAttribute</code> 对象是什么，需要看 <code>AccessDecisionManager</code>的实现者是哪个类，可能是一个简单的角色名称。<code>AbstractSecurityInterceptor</code> 是使用一个 <code>SecurityMetadataSource</code> 对象来获取与受保护对象相关的 <code>ConfigAttribute</code> 集合。在实际使用中， <code>ConfigAttribute</code> 将通过注解的形式定义在受保护的方法上，或者通过 access属性定义在受保护的 URL上。例如 <code>@RolesAllowed({&quot;USER&quot;, &quot;ADMIN&quot;})</code> 或者 <code>&lt;intercept-url pattern=&quot;/user/list&quot; access=&quot;ROLE_USER,ROLE_ADMIN&quot;/&gt;</code> 就表示将 <code>ConfigAttribute ROLE_USER</code>  和 <code>ConfigAttribute ROLE_ADMIN</code> 应用在 <code>/user/list</code> 这个请求的URL 上 在默认的 <code>AccessDecisionManager</code> 实现中，上面的配置就表示用户所拥有的权限中只要拥有一个 <code>GrantedAuthority</code> 与这两个 <code>ConfigAttribute</code> 中的任意一个匹配就允许访问。但是， <code>ConfigAttribute</code> 仅仅只是一个简单的配置属性而已，这个属性具体的含义还是由 <code>AccessDecisionManager</code> 来决定。</p>
<h5 id="2-RunAsManager"><a href="#2-RunAsManager" class="headerlink" title="2. RunAsManager"></a>2. RunAsManager</h5><p>&emsp;&emsp; <code>RunAsManager</code> 意义就是为受保护的对象创建一个临时的 <code>Authenticaion</code>。在 <code>AbstractSecurityInterceptor</code>的<code>beforeInvocation()</code> 方法中，<code>RunAsManager</code> 在 <code>Authentication</code> 认证成功后，会使用原来的 <code>Authenticaion</code>和 <code>ConfigAttribute</code> 构建一个新的 <code>Authenticaion</code>。如果新的 <code>Authenticaion</code>不为空，就产生一个新的 <code>SecurityContext</code>，并把新的 <code>Authenticaion</code> 设置到存放到其中。这样的话，在请求受保护的资源时，从 <code>SecurityContext</code> 中拿到的就是新的 <code>AUthentication</code>。当然，在请求结束后，<code>FilterSecurityInterceptor</code>回调用父类的 <code>finallyInvocation()</code> 方法，把原来的 <code>SecurityContext</code> 重新设置到 <code>SecurityContextHolder</code>中。</p>
<h4 id="2-finallyInvocation-方法"><a href="#2-finallyInvocation-方法" class="headerlink" title="2. finallyInvocation() 方法"></a>2. finallyInvocation() 方法</h4><p>&emsp;&emsp;  在请求结束后，把在 <code>beforeInvocation()</code>方法中修改的 <code>SecurityContext</code> 恢复到原本的 <code>SecurityContext</code>。</p>
<h4 id="3-afterInvocation-方法"><a href="#3-afterInvocation-方法" class="headerlink" title="3. afterInvocation() 方法"></a>3. afterInvocation() 方法</h4><p>&emsp;&emsp; <code>afterInvocation</code> 的主要功能就是受保护的WEB请求调用完成后，对请求的返回值进行修改。其修改返回值的方式和 <code>AuthenticationManager</code>的方式类似，通过其维护的一系列的 <code>AfterInvocationProvider</code>，依次根据是否能够修改该返回值进而修改返回值。当然，修改返回值时也可能会抛出异常，例如后置的权限检查。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Spring-Security/" rel="tag"># Spring Security</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/12/12/2018-12-12-Spring-Security-Source-Analysis-2/" rel="next" title="Spring  Security 源码分析二">
                <i class="fa fa-chevron-left"></i> Spring  Security 源码分析二
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">sangaizhi</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">17</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            
            
              <div class="post-toc-content">  <ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、FilterSecurityInterceptor"><span class="nav-number">1.</span> <span class="nav-text">一、FilterSecurityInterceptor</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、主要职能"><span class="nav-number">1.1.</span> <span class="nav-text">1、主要职能</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2、主要步骤"><span class="nav-number">1.2.</span> <span class="nav-text">2、主要步骤</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、-MethodSecurityInterceptor"><span class="nav-number">2.</span> <span class="nav-text">二、 MethodSecurityInterceptor</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、AbstractSecurityInterceptor"><span class="nav-number">3.</span> <span class="nav-text">三、AbstractSecurityInterceptor</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1、-beforeInvocation-方法"><span class="nav-number">3.1.</span> <span class="nav-text">1、 beforeInvocation() 方法</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-ConfigAttribute"><span class="nav-number">3.1.1.</span> <span class="nav-text">1. ConfigAttribute</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-RunAsManager"><span class="nav-number">3.1.2.</span> <span class="nav-text">2. RunAsManager</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-finallyInvocation-方法"><span class="nav-number">3.2.</span> <span class="nav-text">2. finallyInvocation() 方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-afterInvocation-方法"><span class="nav-number">3.3.</span> <span class="nav-text">3. afterInvocation() 方法</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">sangaizhi</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
